# @Version        : 1.0
# @Update Time    : 2025/9/27 22:29
# @File           : custom_auth.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from typing import Sequence

from sqlalchemy import and_
from sqlalchemy.orm import selectinload

from authx.core.auth_interface import AuthInterface
from src.db.db_database import alchemy
from src.models import SysUser, SysRole
from src.services.user_service import UserService


class CustomAuth(AuthInterface):
    """
    自定义权限认证
    """

    async def get_permission_list(
        self, login_id: str, login_type: str
    ) -> Sequence[str]:
        # 获取权限
        if login_type == "login":
            async with alchemy.with_async_session() as session:
                user = await UserService(session=session).get_one(
                    and_(SysUser.id == int(login_id)),
                    load=[
                        selectinload(SysUser.roles).subqueryload(SysRole.menus),
                    ],
                )
                permissions = list()
                if user.is_super_admin():
                    permissions.append("*:*:*")
                    return permissions
                for role in user.roles:
                    if role.status == "1":
                        for menu in role.menus:
                            if menu.status == "1" and menu.menu_type == "3":
                                permissions.append(menu.permissions)
                return permissions
        return []

    async def get_role_list(self, login_id: str, login_type: str) -> Sequence[str]:
        if login_type == "login":
            # return ["ROLE_ADMIN"]
            async with alchemy.with_async_session() as session:
                user = await UserService(session=session).get_one(
                    and_(SysUser.id == int(login_id)),
                    load=[SysUser.roles],
                )
                if user.is_super_admin():
                    return ["ROLE_ADMIN"]
                roles = list()
                for role in user.roles:
                    if role.status == "1":
                        for menu in role.menus:
                            if menu.status == "1" and menu.menu_type == "3":
                                roles.append(menu.permissions)
                return roles
        return []

    async def is_super_admin(self, login_id: str, login_type: str) -> bool:
        if login_type == "login":
            async with alchemy.with_async_session() as session:
                user = await UserService(session=session).get_one(
                    and_(SysUser.id == int(login_id)),
                    load=[
                        selectinload(SysUser.roles).subqueryload(SysRole.menus),
                    ],
                )
                return user.is_super_admin()
        return False
